import random
import re
import datetime
from . import passport_blue
from flask import request,abort,current_app, make_response, jsonify,session
from info.utils.captcha.captcha import captcha
from info import redis_store, constants, response_code, db
import json
from info.libs.yuntongxun.sms import CCP
from info.models import User

@passport_blue.route('/logout', methods=['GET'])
def logout():
   try:
        session.pop('user_id', None)
        session.pop('mobile', None)
        session.pop('nick_name', None)
   except Exception as e:
       current_app.logger.error(e)
       return jsonify(errno=response_code.RET.DBERR, errmsg='退出登录失败')

   return jsonify(errno=response_code.RET.OK, errmsg='退出成功')


@passport_blue.route('/login', methods=['POST'])
def login():

    json_dict = request.json
    mobile = json_dict.get('mobile')
    password = json_dict.get('password')

    if not all([mobile, password]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='没有接收到数据')
    if not re.match(r'^1[3458][0-9]\d{4,8}$', mobile):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='手机个事错误')

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR,errmsg='查询用户数据失败')

    if not user:
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='用户名或密码错误')

    if not user.check_password(password):
        return jsonify(errno=response_code.RET.PWDERR, errmsg='用户名和密码错误')

    user.last_login = datetime.datetime.now()
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=response_code.RET.DBERR, errmsg='更新最后一次登陆时间失败')

    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name

    return jsonify(errno=response_code.RET.OK, errmsg='登陆成功')


@passport_blue.route('/register', methods=['POST'])
def register():
    json_dict = request.json
    mobile = json_dict.get('mobile')
    smscode_client = json_dict.get('smscode')
    password = json_dict.get('password')


    if not all([mobile, smscode_client, password]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
    if not re.match(r'^1[3458][0-9]\d{4,8}$', mobile):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='手机号格式错误')

    try:
        smscode_server = redis_store.get('SMS:' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询短信验证码失败')

    if not smscode_server:
        return jsonify(errno=response_code.RET.NODATA, errmsg='验证码不存在')

    if smscode_client.lower() != smscode_server.lower():
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='输入验证码有误')

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password#setter方法

    user.last_login = datetime.datetime.now()

    # try:
    #     db.session.add(user)
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    #     db.session.rollback()
    #     return jsonify(errno=response_code.RET.DBERR, errmsg='储存注册数据失败')
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=response_code.RET.DBERR, errmsg='存储注册数据失败')

    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name

    return jsonify(errno=response_code.RET.OK, errmsg='注册成功')


@passport_blue.route('/sms_code', methods=['POST'])
def sms_code():

    json_str = request.data
    json_dict = json.loads(json_str.decode())
    mobile = json_dict.get('mobile')

    image_code_clinet = json_dict.get('image_code')
    image_code_id = json_dict.get('image_code_id')

    if not all([mobile, image_code_clinet, image_code_id]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')

    if not re.match(r'^1[3458][0-9]\d{4,8}$', mobile):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='手机号格式错误')

    try:
        image_code_server = redis_store.get('ImageCode:' + image_code_id)
        #image_code_server = image_code_server_book.decode()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询图片验证码失败')

    if not image_code_server:
        return jsonify(errno=response_code.RET.NODATA, errmsg='图片验证码不存在')

    if image_code_server.lower() != image_code_clinet.lower():
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='验证码输入有误')

    #'%06d':不够6位补0;比如,000034
    sms_code = '%06d' % random.randint(0,999999)
    current_app.logger.error(sms_code)



    # result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
    # print(mobile,type(mobile))
    # print(result)

    # if result != 0:
    #         return jsonify(errno=response_code.RET.THIRDERR, errmsg='验证码发送失败')

    try:
        redis_store.set('SMS:' + mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='存储短信验证码失败')

        #  8.响应发送短信验证码的结果
    return jsonify(errno=response_code.RET.OK, errmsg='发送短信验证码成功')







@passport_blue.route('/image_code')
def image_code():


    imageCodeId = request.args.get('imageCodeId')

    if not imageCodeId:
        abort(403)

    #生成图片验证码:text写入到redis,image响应到浏览器
    name, text, image = captcha.generate_captcha()
    current_app.logger.error(text)

    try:
        redis_store.set('ImageCode:' + imageCodeId, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)

    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpg'


    return response

